package com.yy.util.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.yy.util.bitmap.AsyncBitmapHelper;

/**
 * Created by zhangly on 2015/6/1.
 */
public class ViewHolder {

    private SparseArray<View> mViews;
    private View mConvertView;
    private int mPosition;

    private AsyncBitmapHelper mHelper;

    public ViewHolder(Context context, ViewGroup parent, int layoutId, int position) {
        this(context, parent, layoutId, position, null);
    }

    public ViewHolder(Context context, ViewGroup parent, int layoutId, int position, AsyncBitmapHelper helper) {
        mViews = new SparseArray<View>();
        mConvertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
        mPosition = position;
        mConvertView.setTag(this);
        mHelper = helper;
    }

    public static ViewHolder get(Context context, ViewGroup parent, View convertView, int layoutId, int position, AsyncBitmapHelper helper) {
        if(convertView == null) {
            return new ViewHolder(context, parent, layoutId, position, helper);
        }
        return (ViewHolder) convertView.getTag();
    }

    public <T extends View> T getView(int viewId) {
        View view = mViews.get(viewId);
        if(view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public View getConvertView() {
        return mConvertView;
    }

    public ViewHolder setText(int resId, String text) {
        TextView tv = getView(resId);
        tv.setText(text);
        return this;
    }

    public ViewHolder setImageUrl(int resId, String url) {
        ImageView iv = getView(resId);
        mHelper.loadBitmap(url, iv);
        return this;
    }
}
